// components/dicview/index.js
import {$http} from '@bana/miniapp-common-util'

Component({
  externalClasses: ['container-class', 'dic-class'],
  /**
   * 组件的属性列表
   */
  properties: {
    dicVal: {
      type: Array,
      value: [],
      observer(newVal, oldVal) {
        console.log('dictext dicVal observer=========', newVal, oldVal)
        this._freshStoreDic()
      }
    },
    dicType: {
      type: String,
      value: '',
      observer(newVal, oldVal) {
        console.log('dictext dicType observer=========', newVal, oldVal)
        this._freshStoreDic()
      }
    },
    join: {
      type: String,
      value: ','
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    version: wx.getSystemInfoSync().SDKVersion,
    dicitonary: ''
  },

  attached() {
    this._freshStoreDic()
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _freshStoreDic() {
      const _this = this
      // const dicStore = wx.getStorageSync(_this.data.dicType)
      // if (_this.data.dicType && (dicStore === 'null' || !dicStore)) {
      $http.post({
        url: 'dictionary/findByType',
        data: {
          busiTypeId: _this.data.dicType,
          delFlag: false
        },
        config: {
          storageCache: true
        },
        success(res) {
          // console.log(`${_this.data.dicType} setStorageSync======`, res.data.resultData)
          // wx.setStorageSync(_this.data.dicType, JSON.stringify(res.data.resultData))

          _this._findByType(res.data.resultData)
        }
      })
      // } else {
      //   _this._findByType()
      // }
    },
    _findByType(dictionaryList) {
      // const dictionaryList = wx.getStorageSync(this.data.dicType)
      //   ? JSON.parse(wx.getStorageSync(this.data.dicType)) : []
      if (dictionaryList) {
        if (this.data.dicVal instanceof Array) {
          const dictNameArr = dictionaryList
            .filter(item => this.data.dicVal.includes(item.businId)).map(item => item.businName)
          this.setData({
            dicitonary: dictNameArr.join(this._joinStr())
          })
        } else {
          const dic = dictionaryList.find(item => item.businId === this.data.dicVal)
          if (dic) {
            this.setData({
              dicitonary: dic.businName
            })
          } else {
            this.setData({
              dicitonary: this.data.dicVal
            })
          }
        }
      } else {
        this.setData({
          dicitonary: this.data.dicVal
        })
      }
    },
    _joinStr() {
      return ` ${this.data.join} `
    }
  }
})
